package com.assets.Scrap;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.Adapter.Addrepairs_Adapter1;
import com.assets.bean.AddRepairs_bean1;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Scrap;
import com.assets.room.entity.ScrapScrapdetail;
import com.assets.room.entity.Type;
import com.assets.room.entity.Worker;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.OnDismissListener;
import com.demo.WaveSwipeRefreshLayout;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.bean.AddRepairs_bean;
import com.assets.bean.Property_bean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/3/18.
 */

public class Scrap_dispose extends Activity implements OnDismissListener {
    private ListView lv_poperty;
    private TextView title_text;
    private ImageView fh;
    private List<AddRepairs_bean1> data = new ArrayList<>();
    WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    private String repairsId, details;
    private String datas;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private String url = "http://" + Url.IP + "/api/scrapQueryById";
    // private String eliminate_url = "http://" + Ip_Set.IP + "/api/scrapDelete";
    //private String url_up = "http://" + Ip_Set.IP + "/api/scrapDetailDelete";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repairs_property);
        inview();
        load();
    }

    private void inview() {
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
               /* if (TextUtils.isEmpty(details)) {
                    new AlertView(" 提示！", "退出后，未上传附件的将不申请报废", "取消", new String[]{"确定"}, null, Scrap_dispose.this, AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            //取消：position=-1,确定 position=0
                            if (position == 0) {
                                eliminate();
                            }
                            if (position == -1) {

                            }

                        }
                    }).setCancelable(true).setOnDismissListener(Scrap_dispose.this).show();
                }else {
                    finish();
                }*/
            }
        });
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("报废列表");
        Intent intent = getIntent();
        repairsId = intent.getStringExtra("scrapId");
        details = intent.getStringExtra("details");
        lv_poperty = (ListView) findViewById(R.id.repairs_list);
        lv_poperty.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if (data.get(position).getCategory().equals("已上传附件")) {
                    Intent intent1 = new Intent(Scrap_dispose.this, Scrap_ck.class);
                    intent1.putExtra("repairsId", repairsId);
                    intent1.putExtra("number", data.get(position).getCode_number());
                    intent1.putExtra("Section", data.get(position).getSection());
                    intent1.putExtra("Asset_name", data.get(position).getAsset_name());
                    intent1.putExtra("Model", data.get(position).getModel());
                    intent1.putExtra("remark", data.get(position).getRemark());
                    startActivity(intent1);
                } else {
                    Intent intent1 = new Intent(Scrap_dispose.this, Scrap_Data.class);
                    intent1.putExtra("repairsId", repairsId);
                    intent1.putExtra("number", data.get(position).getCode_number());
                    intent1.putExtra("Section", data.get(position).getSection());
                    intent1.putExtra("Asset_name", data.get(position).getAsset_name());
                    intent1.putExtra("Model", data.get(position).getModel());
                    intent1.putExtra("remark", data.get(position).getRemark());
                    startActivity(intent1);
                }
            }
        });
     /*   if (TextUtils.isEmpty(details)) {
            lv_poperty.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, final int i, long id) {
                    new AlertView(" 提示！", "是否删除", "取消", new String[]{"确定"}, null, Scrap_dispose.this, AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            //取消：position=-1,确定 position=0
                            if (position == 0) {
                                upload(data.get(i).getCode_number());
                            }
                            if (position == -1) {

                            }

                        }
                    }).setCancelable(true).setOnDismissListener(Scrap_dispose.this).show();
                    return true;
                }
            });
        }*/
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(() -> {
            //模拟3秒的加载过程
            //接下来可以刷新ListView
            new Handler().postDelayed(this::load, 1200);
        });
    }

    /*private void eliminate() {
        new Thread() {
            @Override
            public void run() {
                try {
                    OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("scrapId", repairsId)
                            .build();
                    Request request = new Request.Builder()
                            .url(eliminate_url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("222", responseData.toString());
                    showResponse_eliminate(responseData);

                } catch (IOException e) {
                    e.printStackTrace();

                }


            }
        }.start();
    }*/

    private void showResponse_eliminate(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")) {
                        finish();
                    } else finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /*private void upload(final String code_number) {
        new Thread() {
            @Override
            public void run() {
                try {
                    OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("scrapId", repairsId)
                            .add("assetNumber", code_number)
                            .build();
                    Request request = new Request.Builder()
                            .url(url_up)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("222", responseData.toString());
                    showResponse_up(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }*/

    private void showResponse_up(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")) {
                        load();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void load() {

        Scrap scrap = MyDataBase.init(Scrap_dispose.this).scrapService().getScrapById(repairsId);
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        if (scrap != null) {
            List<ScrapScrapdetail> scrapdetails = MyDataBase.init(Scrap_dispose.this).scrapScrapdetailService().getDetailById(repairsId);
            for (ScrapScrapdetail scrapdetail : scrapdetails) {
//                Asset asset = v
                Asset asset = MyDataBase.init(Scrap_dispose.this).assetDao().queryAllByIds(scrapdetail.getAssetId());
                Map<String, Object> map = new HashMap<String, Object>();
//                Dept dept = deptService.getById(asset.getUserDept());
//                Dept dept = MyDataBase.init(Scrap_dispose.this).deptDao().getDeptById(asset.getDeptId());
//                if(dept!=null) {
//                    asset.setDeptId(dept.getSimpleName());
//                }else {
//                    asset.setDeptId("暂无部门");
//                }

                asset.setDeptId(MyDataBase.init(Scrap_dispose.this).scrapService().getScrapById(repairsId).getCreatedate());
//                if(asset.getUserId()!=null && !asset.getUserId().equals("")) {
//                    Worker worker = MyDataBase.init(Scrap_dispose.this).workerService().getWorkerById(Since_case.getInstance().getUserId());/*workerService.getById(asset.getUserId());*/
//                    if(worker!=null) {
//                        asset.setUserId(Since_case.getInstance().getUserId());
//                    }else {
//                        asset.setUserId("暂无使用人");
//                    }
//                }else {
//                    asset.setUserId("暂无使用人");
//                }
                String userId = MyDataBase.init(Scrap_dispose.this).scrapService().getScrapById(repairsId).getUserId();
                asset.setUserId(MyDataBase.init(Scrap_dispose.this).userDao().getNameById(userId) == null ? "暂无此人" : MyDataBase.init(Scrap_dispose.this).userDao().getNameById(userId));
                Type type = MyDataBase.init(Scrap_dispose.this).typeDao().getAllById(asset.getType());
//                Type type = typeService.getById(asset.getType());
                if(type!=null) {
                    asset.setType(type.getName());
                }
                map.put("assetNumber", asset.getAssetNumber());
                map.put("deptId", asset.getDeptId());
                map.put("userId", asset.getUserId());
                map.put("model", asset.getModel());
					/*if(scrap.getStatus().equals("0")) {
						map.put("status", scrapdetail.getStatus());
					}*/
                map.put("status", scrapdetail.getStatus());
                map.put("assetName", asset.getAssetName());
                map.put("remark", scrapdetail.getText());
                map.put("image", asset.getImage());
                maps.add(map);
            }
        }
        showResponse(new Gson().toJson(maps));

//        new Thread() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient client = new OkHttpClient
//                            .Builder()
//                            .hostnameVerifier(new AllowAllHostnameVerifier())
//                            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                            .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                            .readTimeout(500, TimeUnit.SECONDS)
//                            .build();
//                    RequestBody requestBody = new FormBody.Builder()
//                            .add("scrapId", repairsId)
//                            .build();
//                    Request request = new Request.Builder()
//                            .url(url)
//                            .post(requestBody).build();
//                    Response response = client.newCall(request).execute();
//                    String responseData = response.body().string();
//                    showResponse(responseData);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
    }

    private void showResponse(final String responseData) {
        LogUtils.d(responseData);
        Log.d("这个是什么几把", "responseData: " + responseData);
        runOnUiThread(() -> {
            if (responseData.equals("[]")) {
                Toast.makeText(Scrap_dispose.this, "无数据", Toast.LENGTH_SHORT).show();
                // finish();
            }
            list.clear();
            data.clear();
            mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
            Gson gson = new Gson();
            List<Property_bean> userList = gson.fromJson(responseData, new TypeToken<List<Property_bean>>() {
            }.getType());
            for (int i = 0; i < userList.size(); i++) {
                String assetName = userList.get(i).getAssetName();
                String deptId = userList.get(i).getDeptId();
                String assetNumber = userList.get(i).getAssetNumber();
                String userId = userList.get(i).getUserId();
                String model = userList.get(i).getModel();
                String type = "";
                if (userList.get(i).getStatus().equals("1")) {
//                    type = "待上传附件";
                    type = "----";
                }
                if (userList.get(i).getStatus().equals("2")) {
//                    type = "已上传附件";
                    type = "====";
                }
//                remark
                String remark = userList.get(i).getRemark();
//                String remark = jsonObject.getString("remark");
                String image = "";
                if (!TextUtils.isEmpty(userList.get(i).getImage())) {
                    image = "http://" + Url.IP + userList.get(i).getImage();
                    LogUtils.d(image);
                }
                data.add(new AddRepairs_bean1(image, assetName, deptId, assetNumber, userId, model, type, remark, "状态", ""));
            }
            Addrepairs_Adapter1 adapter_item = new Addrepairs_Adapter1(Scrap_dispose.this, R.layout.input_adapter_item, data, "报废");
            lv_poperty.setAdapter(adapter_item);
        });
    }

    @Override
    protected void onRestart() {
        load();
        super.onRestart();

    }

    @Override
    public void onDismiss(Object o) {

    }

    /* @Override
     public void onBackPressed() {
         finish();
         if (TextUtils.isEmpty(details)) {
             new AlertView(" 提示！", "退出后，未上传附件的将不申请报废", "取消", new String[]{"确定"}, null, Scrap_dispose.this, AlertView.Style.Alert, new OnItemClickListener() {
                 @Override
                 public void onItemClick(Object o, int position) {
                     //取消：position=-1,确定 position=0
                     if (position == 0) {
                         eliminate();
                     }
                     if (position == -1) {

                     }
                 }
             }).setCancelable(true).setOnDismissListener(Scrap_dispose.this).show();
         }else {
             finish();
         }
     }*/
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        //判断用户是否点击了“返回键”
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次返回", Toast.LENGTH_SHORT).show();
                //并记录下本次点击“返回键”的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实希望退出程序-调用System.exit()方法进行退出
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
